#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

#include "common.hpp"

int main()
{
    // 创建命名管道文件
    umask(0);
    int n1 = mkfifo(FIFO_FILE, 0666);
    if (n1 == 0)
    {
        std::cout << "mkfifo success." << std::endl;
    }
    else
    {
        std::cerr << "mkfifo fail." << std::endl;
    }

    //打开管道文件
    int fd = open(FIFO_FILE, O_RDONLY);
    if(fd == -1)
    {
        std::cerr << "open fifo fail." << std::endl;
    }
    else
    {
        std::cout << "open fifo success." << std::endl;
    }

    //进行通信：从管道文件中读取

    while(true)
    {
        char buffer[1024];
        int n = read(fd, buffer, sizeof(buffer) - 1);
        if(n > 0)
        {
            buffer[n] = 0;//保证字符串安全
            std::cout << "read fifo success." << std::endl;
            std::cout << "cilent say# " << buffer << std::endl;
        }
        else if(n == 0)
        {
            std::cout << "cilent quit! me too." << std::endl;
            break;
        }
        else
        {
            std::cerr << "read fifo fail" << std::endl;
            break;
        }
    }

    //关闭管道文件
    close(fd);

    // 删除命名管道
    int n2 = unlink(FIFO_FILE);
    if (n2 == 0)
    {
        std::cout << "unlink fifo success" << std::endl;
    }
    else
    {
        std::cerr << "unlink fifo fail" << std::endl;
    }
    return 0;
}